package com.gray.blog.common.result;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gray.blog.common.enums.ErrorCodeEnum;
import java.io.Serializable;
import lombok.Data;

/**
 * Created  By zhoux 2018/10/29
 **/
@Data
public class ModelResult<T> implements Serializable {

    private int errCode;
    private String errMsg;
    private T data;

    public ModelResult() {
    }

    public ModelResult(ErrorCodeEnum code) {
        this.errCode = code.getErrorCode();
        this.errMsg = code.getErrorMessage();
    }

    public ModelResult(int errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public ModelResult(int errCode, String errMsg, T data) {
        this.errCode = errCode;
        this.errMsg = errMsg;
        this.data = data;
    }

    public ModelResult(ErrorCodeEnum code, T data) {
        this.errCode = code.getErrorCode();
        this.errMsg = code.getErrorMessage();
        this.data = data;
    }

    @JsonIgnore
    public boolean isSuccess() {
        return errCode == 0;
    }

    public static <E> ModelResult<E> newSuccess(){
        return new ModelResult<>(ErrorCodeEnum.SUCCESS);
    }

    public static <E> ModelResult<E> newSuccess(E data){
        return new ModelResult<>(ErrorCodeEnum.SUCCESS, data);
    }

    public static <E> ModelResult<E> newError(ErrorCodeEnum code){return new ModelResult<>(code); }

    public static <E> ModelResult<E> newError(int errCode, String errMsg){return new ModelResult<>(errCode, errMsg); }

}
